package com.tjbklx1.beanutils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.Converter;

/***
 * po vo转换
 * ClassName:BeanUtils.java
 * @author Sam Tan
 * @Description TODO
 * @date 2017年11月20日
 */
public class BeanUtils extends BeanUtilsBean{
	
	private static BeanUtils instance = new BeanUtils();
	
	private static CustomDateConvert customDateConvert = new CustomDateConvert();
	
	public static BeanUtils getInstance(){
		return instance;
	}
	
	public static <T> List<T> transfers(List<?> pos,Class<T> voType)  throws TransferException{
		try {
			return getInstance().transfers(pos, voType, null);
		} catch (Exception e) {
			throw new TransferException(e);
		}
		
	}
	
	public static <T> T transfer(Object pos,Class<T> voType) throws TransferException{
		T t = null;
		if(pos != null){
			try {
				t = voType.newInstance();
				getInstance().transfer(pos, t);
			} catch (Exception e) {
				throw new TransferException(e);
			}
		}
		return t;
	}
	
	public void transfer(Object po,Object vo) throws TransferException{
		 try {
			 copyProperties(vo, po);
		} catch (Exception e) {
			throw new TransferException(e); 
		}
	}
	
	public <T> List<T> transfers(List<?> pos,Class<T> voType,T tt) throws TransferException{
		
		try {
			if(pos != null && pos.size() > 0){
				List<T> vos = new ArrayList<T>();
				for (Object po : pos) {

					T t = (T)voType.newInstance();
					transfer(po, t);
					vos.add(t);
				}
				return vos;
			}
		} catch (Exception e) {
			throw new TransferException(e); 
		}
		

		return new ArrayList<T>();
	}
	
	public static void main(String[] args) {
//		List<D018Response> a = new ArrayList<D018Response>();
//		D018Response p = new D018Response();
//		p.setCreateTime("2017-11-22 09:12:13");
//		p.setMoney("23.32");
//		p.setProjectType("1");
//		a.add(p);
//
//		List<AssetProject> b = transfers(a, AssetProject.class);
//	
//		System.out.println("");
		
//		D018Response p = new D018Response();
//		try {
//			D018Response D018Response = transfer(p, null);
//		} catch (TransferException e) {
//		}
//		System.out.println();
	
	}
	
	  

	protected Object convert(Object value, Class<?> type) {
		Converter converter = getConvertUtils().lookup(type);
		Object converterVal = value;
		if (converter != null && converterVal != null && type != null) {

			if (Date.class.isAssignableFrom(type)
					|| Date.class.isAssignableFrom(value.getClass())) {
				converter = customDateConvert;
			}
			return converter.convert(type, converterVal);
		} else {
			return converterVal;
		}
	}
	  

}
